import os
import sys
import os
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
sys.path.insert(0,BASE_PATH)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "study_apscheduler.settings")
import django
django.setup()

# 导入所需的调度器类和触发器类
from apscheduler.schedulers.background import BackgroundScheduler #后台运行
from apscheduler.schedulers.blocking import BlockingScheduler  #主进程运行，需要单独运行
from apscheduler.triggers.interval import IntervalTrigger #时间间隔
from apscheduler.triggers.cron import CronTrigger #复杂的定时任务
from apscheduler.triggers.date import DateTrigger #一次性定时任务
from apscheduler import events
from datetime import datetime
#定时任务
from schedulers.task import send_alert_data,send_alert_log_data,send_device_data,send_system_data

#日志
from schedulers.config import LISTENER
from schedulers.config import TIME_ZONE,JOB_DEFAULTS,JOB_STORE,Scheduler_Logger #调度器配置

class TheBlockScheduler(object):
    TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
    def __init__(self):
        self.scheduler = self._scheduler_obj()
        self.logger = Scheduler_Logger.get('logger')
    # 1、初始化调度器
    def _scheduler_obj(self):
        obj = BlockingScheduler()
        obj.configure(
            timezone=TIME_ZONE,  # 时区
            job_defaults=JOB_DEFAULTS,  # job的默认配置
            jobstores=JOB_STORE,  # job的存储后端
            gconfig=Scheduler_Logger, #日志记录相关的的配置
        )
        return obj

    # 2、添加任务
    def _add_job(self):
        # 1分钟执行一次
        self.scheduler.add_job(
            send_device_data,
            trigger=IntervalTrigger(minutes=1),
            id='send_device_data',
            replace_existing=True,
            coalesce=True,
            name='推送设备信息'
        )
        # 1分钟执行一次
        self.scheduler.add_job(
            send_alert_data,
            trigger=IntervalTrigger(minutes=1),
            id='send_alert_data',
            replace_existing=True,
            coalesce=True,
            name='推送告警信息'
        )
        # 1分钟执行一次
        self.scheduler.add_job(
            send_system_data,
            trigger=IntervalTrigger(minutes=1),
            id='send_system_data',
            replace_existing=True,
            coalesce=True,
            name='推送系统信息'
        )
        # 1分钟执行一次
        self.scheduler.add_job(
            send_alert_log_data,
            trigger=IntervalTrigger(minutes=1),
            id='send_alert_log_data',
            replace_existing=True,
            coalesce=True,
            name='推送振动告警数据'
        )
    # 3、添加监听器
    def _listener(self, event: events):
        code = event.code
        run_time = datetime.now().strftime(self.TIME_FORMAT)
        msg = LISTENER.get(code)

        if code in [4096,8192,16384]:
            # 成功运行
            job_id = event.job_id
            job = self.scheduler.get_job(job_id)
            name = job.name
            self.logger.info(f'job_id={job_id},任务描述={name},运行时间={run_time},执行情况={msg}')

        elif code in (2,4,8,32,128,1024,2048):
            ###调度器启动时
            self.logger.info(msg)
            try:
                job_id = event.job_id
                job = self.scheduler.get_job(job_id)
                name = job.name
                msg = f'job_id={job_id},任务描述={name},运行时间={run_time},执行情况={msg}'
                self.logger.info(msg)
            except Exception:
                msg = f'事件code={code},运行时间={run_time},执行情况={msg}'
                self.logger.info(msg)
    # 4、启动定时器
    def start(self):
        # 1、设置定时任务(监听器会先监听到任务添加，再监听到调度器启动)
        self._add_job()
        # 2、设置监听器
        self.scheduler.add_listener(self._listener)
        # 3、启动调度器
        try:
            self.scheduler.start()
        except KeyboardInterrupt:
            self.scheduler.shutdown()


if __name__ == '__main__':
    #后台启动
    backScheduler = TheBlockScheduler()
    backScheduler.start()